var Feng = {
    ctxPath: "",
    addCtx: function (ctx) {
        if (this.ctxPath == "") {
            this.ctxPath = ctx;
        }
    },
    confirm: function (tip, ensure) {//询问框
        parent.layer.confirm(tip, {
            btn: ['确定', '取消']
        }, function (index) {
            ensure();
            parent.layer.close(index);
        }, function (index) {
            parent.layer.close(index);
        });
    },
    pass:function (data,success) {
        var callback;
        if(data==null){
            Feng.error("请求出错,没有返回任何有效值");
        }else{
            //给回调函数一个参数  并且返回
            if(data.code=="200"){
                callback = success(callback);
            }else{
                Feng.error(data.msg);
            }
        }
        return callback;
    },
    log: function (info) {
        console.log(info);
    },
    alert: function (info, iconIndex) {
        parent.layer.msg(info, {
            icon: iconIndex
        });
    },
    info: function (info) {
        Feng.alert(info, 0);
    },
    success: function (info) {
        Feng.alert(info, 1);
    },
    error: function (info) {
        Feng.alert(info, 2);
    },
    infoDetail: function (title, info) {
        var display = "";
        if (typeof info == "string") {
            display = info;
        } else {
            if (info instanceof Array) {
                for (var x in info) {
                    display = display + info[x] + "<br/>";
                }
            } else {
                display = info;
            }
        }
        parent.layer.open({
            title: title,
            type: 1,
            skin: 'layui-layer-rim', //加上边框
            area: ['950px', '600px'], //宽高
            content: '<div style="padding: 20px;">' + display + '</div>'
        });
    },
    writeObj: function (obj) {
        var description = "";
        for (var i in obj) {
            var property = obj[i];
            description += i + " = " + property + ",";
        }
        layer.alert(description, {
            skin: 'layui-layer-molv',
            closeBtn: 0
        });
    },
    showInputTree: function (inputId, inputTreeContentId, leftOffset, rightOffset) {
        var onBodyDown = function (event) {
            if (!(event.target.id == "menuBtn" || event.target.id == inputTreeContentId || $(event.target).parents("#" + inputTreeContentId).length > 0)) {
                $("#" + inputTreeContentId).fadeOut("fast");
                $("body").unbind("mousedown", onBodyDown);// mousedown当鼠标按下就可以触发，不用弹起
            }
        };

        if (leftOffset == undefined && rightOffset == undefined) {
            var inputDiv = $("#" + inputId);
            var inputDivOffset = $("#" + inputId).offset();
            $("#" + inputTreeContentId).css({
                left: inputDivOffset.left + "px",
                top: inputDivOffset.top + inputDiv.outerHeight() + "px"
            }).slideDown("fast");
        } else {
            $("#" + inputTreeContentId).css({
                left: leftOffset + "px",
                top: rightOffset + "px"
            }).slideDown("fast");
        }

        $("body").bind("mousedown", onBodyDown);
    },
    baseAjax: function (url, tip) {
        var ajax = new $ax(Feng.ctxPath + url, function (data) {
                Feng.pass(data,function () {
                    Feng.success(tip + "成功!");
                });
        }, function (data) {
            Feng.error(tip + "失败!" + data.msg + "!");
        });
        return ajax;
    },
    changeAjax: function (url) {
        return Feng.baseAjax(url, "修改");
    },
    zTreeCheckedNodes: function (zTreeId) {
        var zTree = $.fn.zTree.getZTreeObj(zTreeId);
        var nodes = zTree.getCheckedNodes();
        var ids = "";
        for (var i = 0, l = nodes.length; i < l; i++) {
            ids += "," + nodes[i].id;
        }
        return ids.substring(1);
    },
    eventParseObject: function (event) {//获取点击事件的源对象
        event = event ? event : window.event;
        var obj = event.srcElement ? event.srcElement : event.target;
        return $(obj);
    },
    sessionTimeoutRegistry: function () {
        $.ajaxSetup({
            contentType: "application/x-www-form-urlencoded;charset=utf-8",
            complete: function (XMLHttpRequest, textStatus) {
                //通过XMLHttpRequest取得响应头，sessionstatus，
                var sessionstatus = XMLHttpRequest.getResponseHeader("sessionstatus");
                if (sessionstatus == "timeout") {
                    //如果超时就处理 ，指定要跳转的页面
                    window.location = Feng.ctxPath + "/global/sessionError";
                }
            }
        });
    },
    initValidator: function (formId, fields) {
        $('#' + formId).bootstrapValidator({
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: fields,
            live: 'enabled',
            message: '该字段不能为空'
        });
    },
    underLineToCamel: function (str) {
        var strArr = str.split('_');
        for (var i = 1; i < strArr.length; i++) {
            strArr[i] = strArr[i].charAt(0).toUpperCase() + strArr[i].substring(1);
        }
        var result = strArr.join('');
        return result.charAt(0).toUpperCase() + result.substring(1);
    },
    randomNum: function (minNum, maxNum) {
        switch (arguments.length) {
            case 1:
                return parseInt(Math.random() * minNum + 1, 10);
                break;
            case 2:
                return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
                break;
            default:
                return 0;
                break;
        }
    },
    newCrontab: function (href, menuName) {
        var dataUrl = href;
        var needCreateCrontab = true;

        // 轮询已有的标签，判断是否已经存在标签
        parent.$('.J_menuTab').each(function () {
            if ($(this).data('id') == dataUrl) {
                if (!$(this).hasClass('active')) {
                    $(this).addClass('active').siblings('.J_menuTab').removeClass('active');
                    parent.MyCrontab.scrollToTab(this);
                    parent.MyCrontab.$('.J_mainContent .J_iframe').each(function () {
                        if ($(this).data('id') == dataUrl) {
                            $(this).show().siblings('.J_iframe').hide();
                            $(this).attr('src', $(this).attr('src'));
                            return false;
                        }
                    });
                }
                needCreateCrontab = false;
                return false;
            }
        });

        //创建标签
        if (needCreateCrontab) {
            var tabLink = '<a href="javascript:;" class="active J_menuTab" data-id="' + dataUrl + '">' + menuName + ' <i class="fa fa-times-circle"></i></a>';
            parent.$('.J_menuTab').removeClass('active');
            parent.$('.J_menuTabs .page-tabs-content').append(tabLink);

            var iframeContent = '<iframe class="J_iframe" name="iframe' + Feng.randomNum(100,999) + '" width="100%" height="100%" src="' + dataUrl + '" frameborder="0" data-id="' + dataUrl + '" seamless></iframe>';
            parent.$('.J_mainContent').find('iframe.J_iframe').hide().parents('.J_mainContent').append(iframeContent);
            parent.MyCrontab.scrollToTab($('.J_menuTab.active'));
        }
    },
    initWangEditor: function (options) {
        // 全屏插件
        window.wangEditor.fullscreen = {
            init: function(editorSelector) {
                $(editorSelector + " .w-e-toolbar").append('<div class="w-e-menu"><a class="_wangEditor_btn_fullscreen" href="###" onclick="window.wangEditor.fullscreen.toggleFullscreen(\'' + editorSelector + '\')" data-toggle="tooltip" data-placement="bottom" title data-original-title="全屏编辑"><i class="fa fa-expand"></i></a></div>')
            },
            toggleFullscreen: function(editorSelector) {
                $(editorSelector).toggleClass('fullscreen-editor');
                var $a = $(editorSelector + ' ._wangEditor_btn_fullscreen');
                var $i = $a.find("i:first-child");
                if ($i.hasClass("fa-expand")) {
                    $a.attr("data-original-title", "退出全屏");
                    $i.removeClass("fa-expand").addClass("fa-compress")
                } else {
                    $a.attr("data-original-title", "全屏编辑");
                    $i.removeClass("fa-compress").addClass("fa-expand")
                }


            }
        };
        var $op = $.extend({
            id: "wangEditor",
            contentId: "content",
            uploadUrl: "",
            uploadFileName: "file"
        }, options);
        var E = window.wangEditor;
        editor = new E('#' + $op.id);
        // 通过 url 参数配置 debug 模式。url 中带有 wangeditor_debug_mode=1 才会开启 debug 模式
        editor.customConfig.debug = location.href.indexOf('wangeditor_debug_mode=1') > 0;
        // 关闭粘贴样式的过滤
        editor.customConfig.pasteFilterStyle = false;
        editor.customConfig.zIndex = 100;

        var $content = $('#' + $op.contentId);
        editor.customConfig.onchange = function (html) {
            // 监控变化，同步更新到 textarea
            $content.val(html);
        };

        if ($op.uploadUrl) {
            // 上传图片到服务器
            editor.customConfig.uploadImgServer = $op.uploadUrl;
            editor.customConfig.uploadFileName = 'file';
            // 将图片大小限制为 5M
            editor.customConfig.uploadImgMaxSize = 5 * 1024 * 1024;
            editor.customConfig.customAlert = function (info) {
                // info 是需要提示的内容
                Feng.error(info);
            };
            editor.customConfig.uploadImgHooks = {
                error: function (xhr, editor) {
                    Feng.error("图片上传出错");
                },
                timeout: function (xhr, editor) {
                    Feng.error("请求超时");
                },
                customInsert: function (insertImg, result, editor) {
                    // 图片上传并返回结果，自定义插入图片的事件（而不是编辑器自动插入图片！！！）
                    // insertImg 是插入图片的函数，editor 是编辑器对象，result 是服务器端返回的结果
                    console.log('customInsert：' + insertImg, result, editor);
                    if (result.status == 200) {
                        console.log(result.data);
                        var imgFullPath = appConfig.aliossPath + result.data + appConfig.qiniuImgStyle;
                        editor.txt.append('<img src="' + imgFullPath + '" alt="" style="width: 95%;max-width: 100%;height: auto;border-radius: 6px;"/>');
                        // 解决上传完图片如果未进行其他操作，则不会触发编辑器的“change”事件，导致实际文章内容中缺少最后上传的图片文件 2018-07-13
                        $content.val(editor.txt.html());
                    } else {
                        Feng.error(result.message);
                    }
                }
            };
        }
        editor.create();
        E.fullscreen.init('#' + $op.id);
        // 修改编辑器大小
        editor.$textContainerElem.css('height', '100%');

        // editor.$textContainerElem.css('max-height', '315px').css('height', '100%');
    },
    initMdEditor: function (options) {
        var $op = $.extend({
            id: "mdEditor",
            uniqueId: "mdEditor_1",
            uploadUrl: ""
        }, options);

        // js实现aop切面编程，实时保存文章内容
        Function.prototype.after = function (afterfn) {
            //这里的this是指调用者SimpleMDE.prototype.autosave
            var __self = this;
            //保存原函数的引用
            return function () {
                //返回包含了原函数和新函数的"代理"函数
                //先执行代理函数  也就是showMsg
                afterfn.apply(this, arguments);//(1)
                //执行新函数,且保证this不被劫持,新函数接受的参数
                //也会被原封不动地传入原函数,新函数在原函数之前执行
                //__self也就是指的是SimpleMDE.prototype.autosave方法得到执行
                return __self.apply(this, arguments);//(2)
                //执行原函数并返回原函数的执行结果
                //并且保证this不被劫持
            }
        };
        var showMsg = function () {
            Feng.showSuccessMessage("自动保存完成");
            // var $div = $('<div></div>');
            // $div.css({
            //     'position': 'absolute',
            //     'right': '10px',
            //     'top': 0,
            //     'padding': '5px',
            //     'font-size': '12px',
            //     'color': '#ccc',
            //     'opacity': 0
            // });
            // $div.html("自动保存完成");
            // $div.appendTo($(".CodeMirror"));
            // $div.animate({opacity: 1}, 1000, function () {
            //     $div.animate({opacity: 0}, 1000, function () {
            //         $(this).remove();
            //     })
            // })
        };
        SimpleMDE.prototype.autosave = SimpleMDE.prototype.autosave.after(showMsg);
        simplemde = new SimpleMDE({
            // textarea的DOM对象
            element: document.getElementById($op.id),
            // 自动下载FontAwesome，设为false为不下载(如果设为false则必须手动引入)
            autoDownloadFontAwesome: false,
            // 自动聚焦输入框
            autofocus: true,
            // 是否自动保存正在编写的文本
            // 原理就往本地栈里面放置 key是:"smde_" + op.uniqueId的值,但是保存的时候记得移除 localStorage.setItem(key, value);
            autosave: {
                // 启用自动保存功能
                enabled: true,
                // 自动保存的间隔，以毫秒为单位。默认为10000（10s）
                delay: 10000,
                // 唯一的字符串标识符(保证每个SimpleMDE编辑器的uniqueId唯一)
                uniqueId: $op.uniqueId,
                msg: "自动保存成功了"
            },
            placeholder: "请输入文本内容",
            // 如果设置为true，则会出现JS警报窗口，询问链接或图像URL(插入图片或链接弹窗)。默认为false
            promptURLs: true,
            renderingConfig: {
                // 如果设置为true，将使用highlight.js高亮显示。默认为false
                codeSyntaxHighlighting: true
            },
            showIcons: ["code", "table", "clean-block", "horizontal-rule"],
            tabSize: 4,
            // 编辑器底部的状态栏
            status: true,
            status: ["autosave", "lines", "words", "cursor"], // Optional usage
            status: ["autosave", "lines", "words", "cursor", {
                className: "keystrokes",
                defaultValue: function (el) {
                    this.keystrokes = 0;
                    el.innerHTML = "0 Keystrokes";
                },
                onUpdate: function (el) {
                    el.innerHTML = ++this.keystrokes + " Keystrokes";
                }
            }]
        });
        //重写markdown编辑器的全屏按钮
        var $fullscreen = $(".editor-toolbar a.fa-arrows-alt, .editor-toolbar a.fa-columns");
        $fullscreen.click(function () {
            var $this = $(this);
            if ($fullscreen.hasClass("active")) {
                $(".CodeMirror, .CodeMirror-scroll").css('max-height', 'none');
            } else {
                $(".CodeMirror, .CodeMirror-scroll").css('max-height', '200px');
            }
        });
        //Simplemde支持图片拖拽和粘贴上传
        if ($op.uploadUrl) {
            inlineAttachment.editors.codemirror4.attach(simplemde.codemirror, {
                uploadUrl: $op.uploadUrl
            });
        }
        // $(".editor-preview-side").addClass("markdown-body");
    },
    uploadPreview: function (opts) {
        var id = opts.id;
        var _this = $("#"+id);
        if(_this==null || _this.length==0){
            _this =$(id);
        }
        var _self = _this[0];
        opts = jQuery.extend({
            imgContainer: "",
            width: 100,
            height: 100,
            suffix: ["gif", "jpeg", "jpg", "bmp", "png"],
            callback: function () {
            }
        }, opts || {});
        _self.getObjectURL = function (file) {
            var url = null;
            if (window.createObjectURL != undefined) {
                url = window.createObjectURL(file)
            } else if (window.URL != undefined) {
                url = window.URL.createObjectURL(file)
            } else if (window.webkitURL != undefined) {
                url = window.webkitURL.createObjectURL(file)
            }
            return url
        };
        _this.change(function () {
            var $this = this;
            if(!opts.imgContainer){
                console.error("未指定imgContainer");
                return;
            }
            var $container = $(opts.imgContainer);
            $container.html('<i class="fa fa-spinner fa-pulse fa-loading"></i>');
            if ($this.value) {
                if (!RegExp("\.(" + opts.suffix.join("|") + ")$", "i").test($this.value.toLowerCase())) {
                    Feng.error("只支持以下几种文件格式：[" + opts.suffix.join("，") + "]");
                    $this.value = "";
                    $container.html('');
                    return false
                }
                var $img = $("<img>");
                try {
                    setTimeout(function () {
                        $container.html('');
                        $img.attr('src', _self.getObjectURL($this.files[0]));
                        $img.addClass("img-responsive img-rounded auto-shake");
                        $img.appendTo($container);
                    }, 1500);
                } catch (e) {
                    Feng.error("当前浏览器不支持图片预览！");
                }
                opts.callback()
            } else {
                $container.html('');
            }
        })
    },
    initToastr: function () {
        if(toastr){
            toastr.options = {
                closeButton: true,
                debug: false,
                progressBar: true,
                positionClass: "toast-top-right",
                onclick: null,
                showDuration: "300",//显示动作时间
                hideDuration: "1000",//隐藏动作时间
                timeOut: "2000",//自动关闭超时时间
                extendedTimeOut: "1000",
                showEasing: "swing",
                hideEasing: "linear",
                showMethod: "fadeIn",
                hideMethod: "fadeOut"
            };
        }
    },
    showInfoMessage: function (message) {
        this.initToastr();
        toastr.info(message);
    },
    showSuccessMessage: function (message) {
        this.initToastr();
        toastr.success(message);
    },
    showWarningMessage: function (message) {
        this.initToastr();
        toastr.warning(message);
    },
    showErrorMessage: function (message) {
        this.initToastr();
        toastr.error(message);
    },
    //编辑新增的时候表单赋值
    formSetData:function (key, val,obj,field){
        if((typeof val == "undefined")){
            if($("#" + key).attr("type")!= "undefined"){
                if($("#" + key).attr("type")=='select'){
                    obj[field][key] = $("#" + key).find("option:selected").val();
                }else if($("#" + key).attr("type")=='checkbox' || $("input[name='"+key+"']").attr("type")=='checkbox'){
                    var value = [];
                    var checkboxs = $("#" + key);
                    if(checkboxs=="undefined" || checkboxs.length==0){
                        checkboxs = $("input[name='"+key+"']");
                    }
                    $(checkboxs).each(function (index,item) {
                        if($(item).is(":checked")){
                            value.push($(item).val());
                        }
                    })
                    if(value.length>0){
                        obj[field][key] = value;
                    }
                }else if($("#" + key).attr("type")=='radio' || $("input[name='"+key+"']").attr("type")=='radio'){
                    var value = null;
                    var radio = $("#" + key);
                    if(radio=="undefined" || radio.length==0){
                        radio = $("input[name='"+key+"']");
                    }
                    $(radio).each(function (index,item) {
                        if($(item).is(":checked")){
                            value = $(item).val();
                        }
                    })
                    if(value!=null){
                        obj[field][key] = value;
                    }
                }else {
                    obj[field][key] = $("#" + key).val();
                }
            }else{
                obj[field][key] = value;
            }
        }else{
            obj[field][key] = val;
        }
        return obj;
    },
    isBlack:function(val){
        if(val==null || $.trim(val)==''){
            return true;
        }else{
            return false;
        }
    },
    //解决bootstrapValidator不能范围单一列验证的问题
    isValidField:function (formId,validteField) {
        var formValidator = $('#'+formId).data('bootstrapValidator');
        formValidator.validateField(validteField);

        var fields = formValidator.getFieldElements(validteField);
        var type   = fields.attr('type');
        var  n      = (('radio' == type) || ('checkbox' == type)) ? 1 : fields.length;

        for (var i = 0; i < n; i++) {
            var $field = $(fields[i]);
            if (formValidator._isExcluded($field)) {
                continue;
            }

            for (var validatorName in formValidator.options.fields[validteField].validators) {
                var status = $field.data('bv.result.' + validatorName);
                if (status == formValidator.STATUS_NOT_VALIDATED || status == formValidator.STATUS_VALIDATING) {
                    return false;
                }

                if (status == formValidator.STATUS_INVALID) {
                    formValidator.$invalidField = $field;
                    return false;
                }
            }
        }



        return true;
    },
    // 这是我们判断是写的方法 对象是否为空
    isEmpty:function(obj) {
        if (typeof obj == "undefined" || obj == null || obj == "") {
            return true;
        } else {
            return false;
        }
    }

};
